import 'package:enterprise_v6_app/app/components/custom_modele/custom_audioplayers.dart';
import 'package:enterprise_v6_app/app/components/dialog/custom_tape_sheet.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/hazard_investigation_code.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/location_util.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/common/simple_choice_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/ins_task_detail_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_currency_arrange_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class SupplementaryDetailsController extends GetxController {
  /// 任务id
  String taskId = Get.arguments['taskId'] as String;

  ///排查结果
  List<SimpleChoiceBean> choiceDataList = [];

  /// 显示标题
  String title = Get.arguments['title'] as String;

  /// isNormal 为 true 巡检项为正常时传递的参数
  InsTaskDetailEntity? detailEntity;

  /// 隐患排查流程部署实体
  /// isNormal 为 false 巡检项为存在隐患时传递的参数
  ProcessCurrencyArrangeEntity arrangeEntity = ProcessCurrencyArrangeEntity();

  /// 流程模板实体
  ProcessListEntity entity = ProcessListEntity();

  /// 隐患排查流程节点信息
  List<ProcessNodesEntity> nodeList = [];

  /// 任务名称
  String get taskName => detailEntity?.troubleshootContent ?? '空';

  /// 排查结果是否正常 默认为true
  bool isNormal = true;

  final GlobalKey<CustomAudioplayersState> globalKey = GlobalKey();

  @override
  void onInit() {
    super.onInit();
    choiceDataList.add(SimpleChoiceBean(id: '1', name: '正常', isChecked: isNormal));
    choiceDataList.add(SimpleChoiceBean(id: '0', name: '存在隐患', isChecked: !isNormal));
    // if (type == 2) {
    //   _detailEntity = Get.arguments['detail'] as InsTaskDetailEntity;
    // }
    // 获取任务详情
    getTaskRecordDetail();
    // 查询流程详情
    getProcessRecordByProcessEncoding();
  }

  /// 获取任务详情
  Future<void> getTaskRecordDetail() async {
    final response = await HttpUtil().generateGetRequest<InsTaskDetailEntity>(Interface.getTaskListByHazardId, queryParameters: {
      'taskId': taskId,
    }).execute();

    response.onSuccess((result) {
      if (result.data != null) {
        detailEntity = result.data;
        update();
      }
    });
  }

  /// 根据流程唯一编码查询流程详情
  /// todo processEncoding 后端提供的 隐患排查 唯一编码字段,目前为写死
  Future<void> getProcessRecordByProcessEncoding() async {
    //根据流程唯一编码查询流程详情
    final res = await HttpUtil().generateGetRequest<ProcessListEntity>(Interface.getProcessRecordByProcessEncoding, queryParameters: {
      'processEncoding': HazardInvestigationCode.processEncoding,
    }).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        entity = result.data!;
        entity.id = '';
        arrangeEntity.rtCertificateField = entity;
        getNode();
      } else {
        Get.back();
        AppToast.showError('获取作业票流程信息失败');
      }
    });
  }

  /// 根据流程唯一编码查询所有节点
  Future<void> getNode() async {
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getNode, queryParameters: {
      'processEncoding': entity.processEncoding!,
    }).execute();
    res.onSuccess((result) {
      nodeList = result.data ?? [];
      for (var node in nodeList) {
        node.id = '';
      }
      arrangeEntity.processNodes = nodeList;
    });
  }

  /// 是否存在隐患切换
  void switchStates(SimpleChoiceBean bean) {
    // 点击正常且之前为存在隐患
    if (bean.id == '1' && !isNormal) {
      isNormal = true;
      //清空之前填写的数据
      cleanData();
    }

    // 点击存在隐患且之前为正常
    if (bean.id == '0' && isNormal) {
      isNormal = false;
      //清空之前填写的数据
      cleanData();
    }
    // if (bean.id == '1') {
    //   isNormal = true;
    // } else {
    //   isNormal = false;
    // }
    // update();
  }

  /// 清空数据
  void cleanData() {
    // 隐患确认人
    arrangeEntity.confirmUserId = '';
    arrangeEntity.confirmBy = '';
    // 巡检描述
    detailEntity!.inspectionDescription = '';
    // 巡检照片
    detailEntity!.inspectionPhotos = [];
    // 巡检视频
    detailEntity!.inspectionVideos = [];
    // 巡检视频
    detailEntity!.inspectionVideos = [];
    update();
  }

  /// 选择隐患确认人
  void selectReportingPersonnel() {
    Get.toNamed(AppRoutes.personnelDepartmentTreePage, arguments: {
      'title': '隐患确认人',
      'type': '3',
      'organizationalInterface': Interface.getDepartmentTree,
      'personnelInterface': Interface.getUserByAdministrationList,
    })?.then((value) {
      if (value != null) {
        final List<DepartmentUserEntity> userList = value as List<DepartmentUserEntity>;
        arrangeEntity.confirmUserId = userList[0].id;
        arrangeEntity.confirmBy = userList[0].nickname;
        update();
      }
    });
  }

  /// 录音
  void onTapTape() {
    CustomTapeSheet(
      onCallBack: (url) {
        detailEntity!.patrolVoices!.add(url);
        globalKey.currentState?.initData();
        update();
      },
    ).showBottomSheetDialog(isDismissible: false);
  }

  /// 提交并结束定位
  void submitAndOverLocation() {
    submitTap();
  }

  /// 提交按钮
  void submitTap() {
    // 设置任务执行状态 0：正常 1：补检 2：容错
    try {
      // 当前时间
      final DateTime currentTime = DateTime.now();
      // 任务结束时间
      final DateTime workEndTime = DateTime.parse(detailEntity!.workEndTime!);
      // 容错截止时间
      final DateTime faultLastTime = DateTime.parse(detailEntity!.faultLastTime!);
      if (currentTime.isBefore(workEndTime)) {
        // 当前时间小于结束时间为正常
        detailEntity!.isInspection = '0';
      } else if (currentTime.isAfter(workEndTime) && currentTime.isBefore(faultLastTime)) {
        // 当前时间在 任务结束时间 和 容错截止时间 之间
        detailEntity!.isInspection = '2';
      } else if (currentTime.isAfter(faultLastTime)) {
        // 当前时间在 容错截止时间 之后
        detailEntity!.isInspection = '1';
      }
    } catch (e) {
      AppLogger.printLog(e.toString());
    }

    // 正常
    if (isNormal) {
      checkNormal();
    } else {
      checkAbnormal();
    }

    // if (type == 1) {
    // } else if (type == 2) {
    //   checkNormal();
    // }
  }

  /// 排查正常的接口
  void checkNormal() async {
    // if (detailEntity!.inspectionDescription!.isEmpty) {
    //   AppToast.showWarning('请输入巡检描述!');
    //   return;
    // }
    // if (detailEntity!.inspectionPhotos!.isEmpty) {
    //   AppToast.showWarning('请输入上传拍摄照片!');
    //   return;
    // }
    // 如果巡检描述为空,默认为正常
    if (detailEntity!.inspectionDescription!.isEmpty) {
      detailEntity!.inspectionDescription = '正常';
    }
    // 修改状态为正常
    detailEntity!.checkStatus = 0;
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.insExecuteTask,
          data: detailEntity!.toJson(),
        )
        .execute(isShowLoading: true);

    res.onSuccess((result) {
      Get.back(result: 'success');
      AppToast.showSuccess('提交成功!');
    });
  }

  /// 存在隐患时调用流程部署(隐患上报)接口
  void checkAbnormal() async {
    if (arrangeEntity.confirmUserId!.isEmpty || arrangeEntity.confirmBy!.isEmpty) {
      AppToast.showWarning('请选择隐患确认人!');
      return;
    }
    if (detailEntity!.inspectionDescription!.isEmpty) {
      AppToast.showWarning('请输入巡检描述!');
      return;
    }
    if (detailEntity!.inspectionPhotos!.isEmpty) {
      AppToast.showWarning('请输入上传拍摄照片!');
      return;
    }
    // 设置基础数据
    arrangeEntity.checkRecordId = detailEntity!.id;
    arrangeEntity.riskEventId = detailEntity!.riskEventId;
    arrangeEntity.riskMeasureId = detailEntity!.riskMeasureId;
    arrangeEntity.riskObjectId = detailEntity!.riskObjectId;
    arrangeEntity.riskTaskId = detailEntity!.checkTaskId;
    arrangeEntity.riskUnitId = detailEntity!.riskUnitId;
    // 任务执行状态 0：正常 1：补检 2：容错
    arrangeEntity.isInspection = detailEntity!.isInspection;
    // 描述
    arrangeEntity.dangerRecordDesc = detailEntity!.inspectionDescription;
    // 图片
    arrangeEntity.dangerImages = detailEntity!.inspectionPhotos;
    // 视频
    arrangeEntity.dangerVideo = detailEntity!.inspectionVideos;
    // 语音
    arrangeEntity.dangerVoice = detailEntity!.patrolVoices;

    //流程部署(隐患上报)
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.processLedgerProcessArrange,
          data: arrangeEntity.toJson(),
        )
        .execute(isShowLoading: true);
    //成功
    res.onSuccess((result) {
      Get.back(result: 'success');
      AppToast.showWarning('隐患上报成功!');
    });
  }
}
